package com.lm.javassist.example;
import com.lm.javassist.inter.Greeting;
import javassist.*;
public class DynamicProxyExample {
    public static void main(String[] args) throws Exception {
        ClassPool pool = ClassPool.getDefault();

        // 创建代理类
        CtClass proxyClass = pool.makeClass("com.example.ProxyClass");
        proxyClass.addInterface(pool.get("com.lm.javassist.inter.Greeting"));

        // 实现接口方法
        CtMethod method = new CtMethod(pool.get("java.lang.String"), "greet", new CtClass[]{pool.get("java.lang.String")}, proxyClass);
        method.setBody("{ return \"Hello, \" + $1 + \"!\"; }");
        proxyClass.addMethod(method);

        // 加载代理类
        Class<?> dynamicProxy = proxyClass.toClass();
        Greeting greeting = (Greeting) dynamicProxy.getDeclaredConstructor().newInstance();

        // 调用代理方法
        System.out.println(greeting.greet("Javassist")); // 输出：Hello, Javassist!
    }
}
